<template>
  <div class="project-detail-container">
    <!-- 项目基本信息 -->
    <el-page-header @back="goBack" />
    <el-card class="info-card">
      <div class="header-section">
        <h1 class="project-title">{{ project.projectName }}</h1>
        <div class="tags-group">
          <el-tag :type="getStatusTagType(project.status)" size="large">
            {{ project.status }}
          </el-tag>
          <el-tag type="info" size="large">
            {{ projectTypeMap[project.type] || project.type }}
          </el-tag>

      <el-button 
        type="primary" 
        @click="handleEdit"
        size="large"
        v-if="shouldShowUploadButton"
      >
        上传文件
      </el-button>

        </div>
      </div>
      
      <el-divider />
      
      <el-descriptions :column="2" border>
        <el-descriptions-item label="项目编号">{{ project.projectCode }}</el-descriptions-item>
        <el-descriptions-item label="投资方">{{ project.investor }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ project.contactPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ project.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="产业类别">
          <el-tag :type="getIndustryTagType(project.industryCategory)">
            {{ project.industryCategory }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="所属园区">{{ project.parkName }}</el-descriptions-item>
        <el-descriptions-item label="项目地址">{{ project.address }}</el-descriptions-item>
        <el-descriptions-item label="开始日期">{{ project.constructionStartDate }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="files-card">
  <h3 class="section-title">项目文件</h3>
  <el-divider />
  
  <!-- 空状态 -->
  <el-empty 
    v-if="projectFiles.length === 0"
    description="暂无项目文件"
    :image-size="100"
  />
  
  <!-- 文件列表 -->
  <div class="file-list">
    <div 
      v-for="file in projectFiles" 
      :key="file.id"
      class="file-item"
    >
      <div class="file-info">
        <el-icon class="file-icon"><Document /></el-icon>
        <span class="file-name">{{ file.name }}</span>
        <span class="file-size">{{ formatFileSize(file.size) }}</span>
      </div>
      <div class="file-actions">
        <el-button 
          type="success" 
          size="small"
          @click="handleDownload(file)"
        >
          下载
        </el-button>
      </div>
    </div>
  </div>
</el-card>

 <!-- 审核进度 -->
  <el-card class="progress-card">
    <h3 class="section-title">审核进度</h3>
    <el-divider />
    
    <div class="approval-progress">
      <!-- 根据项目类型和状态显示不同的进度条 -->
      <template v-if="project.state === 'landApproval'">
        <!-- 征地报批项目的进度条 -->
        <el-steps align-center :active="getActiveStep()">
          <el-step 
            title="勘测定界文件"
            description="县自然资源和规划局"
            :icon="getStepIcon(1)"
            :status="getStepStatus(1)"
          />
          <el-step 
            title="办理征地手续"
            description="县自然资源和规划局"
            :icon="getStepIcon(2)"
            :status="getStepStatus(2)"
          />
          <el-step 
            title="征地卷宗报批"
            description="县自然资源和规划局"
            :icon="getStepIcon(3)"
            :status="getStepStatus(3)"
          />
          <el-step 
            title="土地出让"
            description="县自然资源和规划局"
            :icon="getStepIcon(4)"
            :status="getStepStatus(4)"
          />
          <el-step 
            title="不动产登记审批"
            description="县自然资源和规划局"
            :icon="getStepIcon(5)"
            :status="getStepStatus(5)"
          />
          <el-step 
            title="上传并联事项文件"
            description="县生态环境局"
            :icon="getStepIcon(6)"
            :status="getStepStatus(6)"
          />
          <el-step 
            title="审批并联事项文件"
            description="行政审批局"
            :icon="getStepIcon(7)"
            :status="getStepStatus(7)"
          />
          <el-step 
            title="签订承诺制协议"
            description="行政审批局"
            :icon="getStepIcon(8)"
            :status="getStepStatus(8)"
          />
        </el-steps>
      </template>
      
      <template v-else-if="project.state === 'construction'">
        <!-- 建设中项目的进度条 -->
        <el-steps align-center :active="getActiveStep()">
          <template v-if="project.type === 'rental'">
            <!-- 租赁厂房项目的进度条 -->
            <el-step 
              title="建设发展局" 
              :icon="getStepIcon(1)"
              :status="getStepStatus(1)"
            />
            <el-step 
              title="经济发展局"
              :icon="getStepIcon(2)"
              :status="getStepStatus(2)"
            />
          </template>
          <template v-else>
            <!-- 独立选址项目的进度条 -->
            <el-step 
              v-for="(step, index) in [
                '建设单位', '建设发展局', '建设单位', 
                '县住建局', '行政审批局', '经济发展局'
              ]" 
              :key="index"
              :title="step"
              :icon="getStepIcon(index + 1)"
              :status="getStepStatus(index + 1)"
            />
          </template>
        </el-steps>
      </template>
      
      <template v-else-if="project.state === 'completion'">
        <!-- 竣工验收项目的进度条 -->
        <el-steps align-center :active="getActiveStep()">
          <template v-if="project.type === 'rental'">
            <!-- 租赁厂房项目的进度条 -->
            <el-step 
              title="上传并联事项文件"
              description="县生态环境局"
              :icon="getStepIcon(1)"
              :status="getStepStatus(1)"
            />
            <el-step 
              title="审批并联事项文件"
              description="行政审批局"
              :icon="getStepIcon(2)"
              :status="getStepStatus(2)"
            />
          </template>
          <template v-else>
            <!-- 独立选址项目的进度条 -->
            <el-step 
              title="组织竣工验收"
              description="建设单位"
              :icon="getStepIcon(1)"
              :status="getStepStatus(1)"
            />
            <el-step 
              title="报请部门联合验收"
              description="建设发展局"
              :icon="getStepIcon(2)"
              :status="getStepStatus(2)"
            />
            <el-step 
              title="竣工验收备案"
              description="行政审批局"
              :icon="getStepIcon(3)"
              :status="getStepStatus(3)"
            />
            <el-step 
              title="不动产登记审批"
              description="县自然资源和规划局"
              :icon="getStepIcon(4)"
              :status="getStepStatus(4)"
            />
          </template>
        </el-steps>
      </template>
    </div>
  </el-card>

    <!-- 审核意见详情 -->
    <el-card class="comments-card">
      <h3 class="section-title">审核意见详情</h3>
      <el-divider />

      <!-- 空状态判断 -->
      <el-empty 
      v-if="approvalRecords.length === 0"
      description="暂无审核记录"
      :image-size="100"
      />

      <el-timeline>
        <el-timeline-item
          v-for="(record, index) in sortedApprovalRecords"
          :key="index"
          :timestamp="formatDateTime(record.time)"
          :type="getRecordType(record.status)"
          :color="getRecordColor(record.status)"
          placement="top"
        >
          <el-card>
            <h4>{{ record.department }} - {{ record.status }}</h4>
            <p>{{ record.comment || '无审核意见' }}</p>
            <div class="auditor-info">
              <span>审核人: {{ record.auditor || '系统管理员' }}</span>
               <!-- 新增：重新提交按钮 -->
        <el-button
          v-if="shouldShowResubmitButton(record, index)"
          type="primary"
          size="small"
          @click="handleEdit"
          class="resubmit-button"
        >
          重新提交
        </el-button>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted,computed } from 'vue'
import { useRoute,useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useProjectStore } from '@/stores/project'
import { Document,Clock } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const projectStore = useProjectStore()

const projectId = ref(route.query.projectId)

const goBack = () => {
  router.go(-1)
}

// 判断是否显示重新提交按钮
const shouldShowResubmitButton = (record, index) => {
  // 只对最新记录判断
  if (index !== 0) return false
  
  // 检查是否为驳回状态
  if (record.status !== '已驳回') return false
  
  // 征地报批项目条件：第5步驳回
  const isLandApprovalCondition = 
    project.value.state === 'landApproval' && 
    record.step === 5
  
  // 独立选址+竣工验收项目条件：第4步驳回
  const isIndependentCompletionCondition = 
    project.value.type === 'independent' && 
    project.value.state === 'completion' && 
    record.step === 4
  
  // 满足任一条件即显示按钮
  return isLandApprovalCondition || isIndependentCompletionCondition
}

// 判断是否显示上传文件按钮
const shouldShowUploadButton = computed(() => {
  const records = approvalRecords.value
  if (records.length === 0) return false
  
  // 获取最大步骤记录
  const maxStepRecord = records.reduce((prev, current) => 
    (prev.step > current.step) ? prev : current
  )
  
  // 征地报批项目条件
  const isLandApprovalCondition = 
    project.value.state === 'landApproval' && 
    maxStepRecord.step === 4 && 
    (maxStepRecord.status === '已通过' || maxStepRecord.status === '已提交')
  
  // 竣工验收项目条件
  const isCompletionCondition = 
    project.value.state === 'completion' && 
    maxStepRecord.step === 3 && 
    (maxStepRecord.status === '已通过' || maxStepRecord.status === '已提交')
  
  // 满足任一条件即显示按钮
  return isLandApprovalCondition || isCompletionCondition
})

// 获取项目文件
const projectFiles = computed(() => {
  return projectStore.getProjectFiles(projectId.value)
})

// 文件大小格式化
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 文件下载
const handleDownload = (file) => {
  ElMessage.success(`开始下载: ${file.name}`)
  // 实际项目中这里应该调用文件下载API
}

// 重新提交
const handleEdit = () => {
  const targetPath = project.value.type === 'independent' 
    ? '/indepenapply' 
    : '/rentalapply'
  
  router.push({
    path: targetPath,
    query: {
      projectId: project.value.id,
      editMode: true
    }
  })
}

// 项目类型映射
const projectTypeMap = {
  independent: '独立选址',
  rental: '租赁厂房'
}

// 项目数据
const project = computed(() =>{ 
  return projectStore.getProjectById(projectId.value)
})


// 模拟审核记录数据
const approvalRecords = computed(() => {
  return projectStore.getProjectAuditRecords(projectId.value)
})

// 按ID倒序排列的审核记录
const sortedApprovalRecords = computed(() => {
  return [...approvalRecords.value].sort((a, b) => b.id - a.id)
})

// 获取步骤状态
const getStepStatus = (stepIndex) => {
  const records = approvalRecords.value
  if (!records || records.length === 0) {
    return stepIndex === 1 ? 'process' : 'wait'
  }
  
  // 获取ID最大的记录
  const maxIdRecord = records.reduce((prev, current) => 
    (prev.id > current.id) ? prev : current
  )
  
    // 特殊驳回条件判断
  const isSpecialRejectCondition = 
    (project.value.state === 'landApproval' && maxIdRecord.step === 5 && maxIdRecord.status === '已驳回') ||
    (project.value.type === 'independent' && project.value.state === 'completion' && maxIdRecord.step === 4 && maxIdRecord.status === '已驳回')
  // 当前步骤小于最大ID记录的step值，已完成
  if (stepIndex < maxIdRecord.step - 1) {
    return 'success'
  }
  else if (stepIndex === maxIdRecord.step - 1){
    // 根据最大ID记录的状态返回不同状态
    if (maxIdRecord.status === '已驳回') {
      if (isSpecialRejectCondition) {
        return 'success'
      }
      return 'process'
    } else if (maxIdRecord.status === '已通过' || maxIdRecord.status === '已提交' || maxIdRecord.status === '已更新' ) {
      return 'success'
    }
  }
  // 当前步骤等于最大ID记录的step值
  else if (stepIndex === maxIdRecord.step) {
    // 根据最大ID记录的状态返回不同状态
    if (maxIdRecord.status === '已驳回') {
      if (isSpecialRejectCondition) {
        return 'process'
      }
      return 'wait'
    } else if (maxIdRecord.status === '已通过' || maxIdRecord.status === '已提交' ) {
      return 'success'
    }else {
      return 'process'
    }
  }
  // 当前步骤是最大ID记录的step+1
  else if (stepIndex === maxIdRecord.step + 1) {
    // 只有当maxIdRecord状态为'已通过'或'已提交'时才显示为process
    if (maxIdRecord.status === '已通过' || maxIdRecord.status === '已提交' ) {
      return 'process'
    }

    if (maxIdRecord.status === '已驳回') {
      return 'wait'
    }
    if (maxIdRecord.status === '已更新') {
      return 'wait'
    }
  }
  // 其他情况都是等待中
  else {
    return 'wait'
  }
}

// 获取步骤图标
const getStepIcon = (stepIndex) => {
  const status = getStepStatus(stepIndex)
  if (status === 'process') {
    return Clock // 使用时钟图标
  }
  return undefined // 其他状态不显示图标
}

// 获取当前激活的步骤
const getActiveStep = () => {
  const records = approvalRecords.value
  if (!records || records.length === 0) return 1
  
  // 获取ID最大的记录
  const maxIdRecord = records.reduce((prev, current) => 
    (prev.id > current.id) ? prev : current
  )
  
  // 特殊驳回条件判断
  const isSpecialRejectCondition = 
    (project.value.state === 'landApproval' && maxIdRecord.step === 5 && maxIdRecord.status === '已驳回') ||
    (project.value.type === 'independent' && project.value.state === 'completion' && maxIdRecord.step === 4 && maxIdRecord.status === '已驳回')
  
  if (isSpecialRejectCondition) {
    return maxIdRecord.step // 保持当前步骤
  }
  
  if (maxIdRecord.status === '已通过' || maxIdRecord.status === '已提交') {
    return maxIdRecord.step + 1
  } else if (maxIdRecord.status === '已驳回') {
    return Math.max(maxIdRecord.step - 1, 1) // 其他驳回情况正常减1
  } else {
    return maxIdRecord.step
  }
}

// 格式化时间为 YYYY-MM-DD HH:mm:ss
const formatDateTime = (timeString) => {
  const date = new Date(timeString)
  if (isNaN(date.getTime())) return timeString // 如果解析失败，返回原字符串
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const map = {
    '审核中': 'warning',
    '已通过': 'success',
    '已驳回': 'danger',
    '已完成': 'info'
  }
  return map[status] || ''
}

// 获取产业类别标签类型
const getIndustryTagType = (category) => {
  const map = {
    '智能制造': '',
    '电子信息': 'success',
    '生物医药': 'warning',
    '新能源': 'danger',
    '新材料': 'info'
  }
  return map[category] || ''
}

// 获取审核记录类型
const getRecordType = (status) => {
  const map = {
    '已通过': 'success',
    '已驳回': 'danger',
    '审核中': 'warning'
  }
  return map[status] || ''
}

// 获取审核记录颜色
const getRecordColor = (status) => {
  const map = {
    '已通过': '#67C23A',
    '已驳回': '#F56C6C',
    '审核中': '#E6A23C'
  }
  return map[status] || ''
}

onMounted(() => {
})
</script>

<style scoped>
.project-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.info-card,
.progress-card,
.comments-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.project-title {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.tags-group {
  display: flex;
  gap: 10px;
}

.section-title {
  margin: 0 0 15px 0;
  font-size: 18px;
  color: #333;
}

.approval-progress {
  padding: 20px;
}

:deep(.el-step__title) {
  font-size: 14px;
}

:deep(.el-step__description) {
  font-size: 12px;
}

.auditor-info {
  margin-top: 10px;
  font-size: 13px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  :deep(.el-descriptions) {
    display: block;
  }
  
  :deep(.el-descriptions-item) {
    display: block;
    margin-bottom: 10px;
  }
  
  .approval-progress {
    padding: 10px;
  }
}

/* 文件卡片样式 */
.files-card {
  margin-bottom: 20px;
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.file-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.file-icon {
  margin-right: 8px;
  color: #409EFF;
  font-size: 18px;
}

.file-name {
  margin-right: 8px;
  font-size: 14px;
  color: #606266;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: 12px;
  color: #909399;
}

.file-actions {
  display: flex;
  gap: 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .file-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .file-actions {
    align-self: flex-end;
  }
}

/* 步骤条统一样式 */
:deep(.el-step__head.is-process) {
  color: #e6a23c;
  border-color: #e6a23c;
}

:deep(.el-step__title.is-process) {
  color: #e6a23c;
  font-weight: bold;
}

:deep(.el-step__head.is-success) {
  color: #67C23A;
  border-color: #67C23A;
}

:deep(.el-step__head.is-error) {
  color: #F56C6C;
  border-color: #F56C6C;
}

:deep(.el-step__head.is-wait) {
  color: #C0C4CC;
  border-color: #C0C4CC;
}

/* 时钟图标样式 */
:deep(.el-step__icon.is-process) {
  background-color: #e6a23c;
  color: white;
}

/* 步骤描述跟随状态变色 */
:deep(.el-step__description.is-process) {
  color: #e6a23c;
}

:deep(.el-step__description.is-success) {
  color: #67C23A;
}

:deep(.el-step__description.is-error) {
  color: #F56C6C;
}

:deep(.el-step__description.is-wait) {
  color: #C0C4CC;
}

.approval-progress {
  padding: 20px;
}
</style>